<template>
  <div>
    <div class="gva-table-box">
      <el-table :data="tableData">
        
        <el-table-column
          align="left"
          label="文件名称"
          prop="name"
          min-width="300"
        >
          <template #default="scope">
            <div class="name">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>

        <el-table-column align="left" label="文件类型" prop="tag" min-width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.tag === 'jpg' ? 'primary' : 'success'"
              disable-transitions
              >{{ scope.row.tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="文件权限" prop="tag" min-width="100">
          <template #default="scope">
            <div class="name">
              {{ scope.row.permission ? "公开" : "私有" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="上传用户" prop="tag" min-width="100">
          <template #default="scope">
            <div class="name">
              {{ scope.row.creator }}
            </div>
          </template>
        </el-table-column>

        
        

        <el-table-column align="left" label="上传日期" prop="CreatedAt" min-width="180">
          <template #default="scope">
            <div>{{ formatDate(scope.row.CreatedAt) }}</div>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :style="{ float: 'right', padding: '20px' }"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>

      <!-- <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="日期" width="180">
            <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column sortable align="left" label="样本数据ID" prop="ybsjid" width="120" />
        <el-table-column align="left" label="实验名称" prop="symc" width="120" />
         <el-table-column align="left" label="实验时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.sysj) }}</template>
         </el-table-column>
        <el-table-column align="left" label="实验完成人" prop="sywcr" width="120" />
        <el-table-column align="left" label="实验文件" prop="sywj" width="120" />
        <el-table-column align="left" label="按钮组">
            <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateSampleDataFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div> -->
    </div>

    <!-- ====================================以上为录入弹窗==================================== -->
    <div style="display: flex">
      <!-- <div class="echart" id="mychart" style="width: 30%; height: 600px"></div> -->
      <div
        class="echart"
        id="mychart2"
        style="width: 100%; height: 600px"
      ></div>
      <!-- <div class="echart" id="mychart3" style="width: 30%; height: 600px"></div> -->
    </div>
  </div>
</template>
  
  <script>
export default {
  name: "LineChart",
};
</script>
  
  <script setup>
import {
  createSampleData,
  deleteSampleData,
  deleteSampleDataByIds,
  updateSampleData,
  findSampleData,
  getPeopleNameCount,
  getSampleDataList,
} from "@/api/sampleData";
import {
  getFileList,
  deleteFile,
  editFileName,
  getImg,
} from "@/api/fileUploadAndDownload";
// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
} from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive } from "vue";
import * as echarts from "echarts";
//============以下为上传新增==============
import { useUserStore } from "@/pinia/modules/user";
import { async } from "q";
const emit = defineEmits(["on-success"]);
const path = ref(import.meta.env.VITE_BASE_API);
const userStore = useUserStore();
const fullscreenLoading = ref(false);
//============以上为上传新增==============
// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  ybsjid: 0,
  symc: "",
  sysj: new Date(),
  sywcr: "",
  sywj: "",
});

const piechartmap = [];
const piechartmapKeys = [];
const piechartmapValues = [];

// 验证规则
const rule = reactive({});

const elFormRef = ref();

// =========== 表格控制部分 ===========
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const searchInfo = ref({});
// 排序
const sortChange = ({ prop, order }) => {
  searchInfo.value.sort = prop;
  searchInfo.value.order = order;
  getTableData();
};

// 重置
const onReset = () => {
  searchInfo.value = {};
  getTableData();
};

// 搜索
const onSubmit = () => {
  page.value = 1;
  pageSize.value = 10;
  getTableData();
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

// 查询
const getTableData = async () => {
  const table = await getFileList({
    page: page.value,
    pageSize: pageSize.value,
    globalSearch: true,
    urlPath: 'Dir',
    dir:'/',
    userName: userStore.userInfo.userName,
  });
  console.log(table)
  if (table.code === 0) {
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};
const nationData = ref([]);
// 获取需要的字典 可能为空 按需保留
setOptions();
const getNationCount = async () => {
  await setOptions();
  const result = await getPeopleNameCount();
  console.log("未处理的原始数据如下：");
  console.log(result);
  if (result.code === 0) {
    // nationData.value = result.data.nationCount
    // for(var i = 0;i<nationData.value.length;i++){
    //   let nationname = nationOptions.value.filter(item => item.value === nationData.value[i].Nation)[0].label
    //   let cntvalue = nationData.value[i].Count
    //   piechartmap.push({value:cntvalue,name:nationname})
    //   piechartmapKeys.push(nationname)
    //   piechartmapValues.push(cntvalue)
    // }

    nationData.value = result.data.peopleNameCount;
    for (var i = 0; i < nationData.value.length; i++) {
      let nationname = nationData.value[i].Creator;
      let cntvalue = nationData.value[i].Count;
      piechartmap.push({ value: cntvalue, name: nationname });
      piechartmapKeys.push(nationname);
      piechartmapValues.push(cntvalue);
    }
  }
};

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteSampleDataFunc(row);
  });
};

// 批量删除控制标记
const deleteVisible = ref(false);

// 多选删除
const onDelete = async () => {
  const ids = [];
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的数据",
    });
    return;
  }
  multipleSelection.value &&
    multipleSelection.value.map((item) => {
      ids.push(item.ID);
    });
  const res = await deleteSampleDataByIds({ ids });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--;
    }
    deleteVisible.value = false;
    getTableData();
  }
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 更新行
const updateSampleDataFunc = async (row) => {
  const res = await findSampleData({ ID: row.ID });
  type.value = "update";
  if (res.code === 0) {
    formData.value = res.data.resampleData;
    dialogFormVisible.value = true;
  }
};

// 删除行
const deleteSampleDataFunc = async (row) => {
  const res = await deleteSampleData({ ID: row.ID });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--;
    }
    getTableData();
  }
};

// 弹窗控制标记
const dialogFormVisible = ref(false);

// 打开弹窗
const openDialog = () => {
  type.value = "create";
  dialogFormVisible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false;
  formData.value = {
    ybsjid: 0,
    symc: "",
    sysj: new Date(),
    sywcr: "",
    sywj: "",
  };
};
// 弹窗确定
const enterDialog = async () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    let res;
    switch (type.value) {
      case "create":
        res = await createSampleData(formData.value);
        break;
      case "update":
        res = await updateSampleData(formData.value);
        break;
      default:
        res = await createSampleData(formData.value);
        break;
    }
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "创建/更改成功",
      });
      closeDialog();
      getTableData();
    }
  });
};

//=============================以下为批量导入弹窗=================================
const fileList = [];
//批量导入弹窗控制标记
const dialogFormVisible2 = ref(false);
//打开批量导入弹窗
const openDialog2 = () => {
  dialogFormVisible2.value = true;
};
//关闭批量导入弹窗
const closeDialog2 = () => {
  dialogFormVisible2.value = false;
  formData.value = {
    ybsjid: 0,
    symc: "",
    sysj: new Date(),
    sywcr: "",
    sywj: "",
  };
  fileList.splice(0, fileList.length);
};
//=============================以上为批量导入弹窗=================================

// =======================================以下为新增==============================================
const arr = [];

const data = [];
const handleChange = (file) => {
  fileList.splice(0, fileList.length);
  fileList.push({ name: file.name });
  data.push({ file: file });
  //importfxx(file.raw);
};
const importfxx = (obj) => {
  var rABS = false; //是否将文件读取为二进制字符串
  var f = obj;
  var reader = new FileReader();

  FileReader.prototype.readAsBinaryString = function (f) {
    var binary = "";
    var rABS = false; //是否将文件读取为二进制字符串
    var pt = this;
    var wb; //读取完成的数据
    var outdata;
    var reader = new FileReader();
    reader.onload = function (e) {
      var bytes = new Uint8Array(reader.result);
      var length = bytes.byteLength;
      for (var i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      //var XLSX = require("xlsx");
      if (rABS) {
        wb = XLSX.read(btoa(fixdata(binary)), {
          //手动转化
          type: "base64",
        });
      } else {
        wb = XLSX.read(binary, {
          type: "binary",
        });
      }
      outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
      console.log("未处理的原始数据如下：");
      console.log(outdata);
      //此处可对数据进行处理

      outdata.map(async (v) => {
        let obj = {};
        //============================数据转换开始==========================

        let temp = ref({
          cZPTID: 0,
          gJ: undefined,
          dQ: "",
          pTLX: undefined,
          pTXH: undefined,
          zZDW: "",
          tXZBSL: 0,
          qBLY: "",
          bZ: "",
        });

        temp.value = {
          cZPTID: v["承载平台ID"],
          gJ: v["国家"],
          dQ: v["地区"],
          pTLX: v["平台类型"],
          pTXH: v["平台型号"],
          zZDW: v["作战单位"],
          tXZBSL: v["通信装备数量"],
          qBLY: v["QB来源"],
          bZ: v["备注"],
        };
        arr.push(temp);
      });
    };
    reader.readAsArrayBuffer(f);
  };
  if (rABS) {
    reader.readAsArrayBuffer(f);
  } else {
    reader.readAsBinaryString(f);
  }
};

const ensureImport = async () => {
  let temp = ref({});
  temp.value = {
    ybsjid: formData.value.ybsjid,
    symc: formData.value.symc,
    sysj: formData.value.sysj,
    sywcr: formData.value.sywcr,
    sywj: fileList[fileList.length - 1].name,
    // fileList.length-1
  };
  fileList.splice(0, 1);
  //fileList.pop

  // console.log('文件内容如下：');
  // console.log(temp);
  // console.log('文件名如下：');
  // console.log(fileList[0].name);
  // ElMessage({
  //     type: 'success',
  //     message: '执行到ensureImport了'
  //   })
  let res = await createSampleData(temp.value);
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "创建/更改成功",
    });
    closeDialog2();
    getTableData();
  }
  // ElMessage({
  //   type: 'success',
  //   message: '到ensureImport了'
  // })
  // arr.forEach(async (formData)=>{
  //   let res = await createPlatform(formData.value);
  // })
  // closeDialog2();
  // setTimeout(()=>{
  //   getTableData();
  // },500);

  // ElMessage({
  //   type: 'success',
  //   message: '导入成功'
  // })
};
// =======================================以上为新增==============================================

const checkFile = (file) => {
  // ElMessage({
  //   type: 'error',
  //   message: '执行到checkFile了？'
  // })
  // fullscreenLoading.value = true
  // const isExcel = file.type === "application/vnd.ms-excel";
  // const isXML = file.type === "text/xml";
  // const isLt2M = file.size / 1024 / 1024 < 0.5
  // if (!isExcel && !isXML) {
  //   this.$message.error("只能上传Excel或XML文件");
  //   return false;
  // }
  // if (!isLt2M) {
  //   ElMessage.error('上传文件大小不能超过 500KB')
  //   fullscreenLoading.value = false
  // }
  // return  isLt2M
  return true;
};
const entureUpload1 = ref(false);
const uploadSuccess = (res) => {
  // const { data } = res
  return;
  ElMessage({
    type: "error",
    message: "执行到uploadSuccess了",
  });
  if (data.file) {
    emit("on-success", data.file.url);
  }
  entureUpload1.value = false;
};

const entureUpload = () => {
  // entureUpload1.value=true;
  // uploadSuccess()
  // if (data.file) {
  //   emit('on-success', data.file.url)
  // }
};

const uploadError = () => {
  ElMessage({
    type: "error",
    message: "上传失败",
  });
  fullscreenLoading.value = false;
};

const initcharts = async () => {
  let option = {
    title: {
      text: "每人完成实验个数",
      left: "center",
      bottom: "5%",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      top: "5%",
      left: "center",
    },
    series: [
      {
        name: "Form",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: piechartmap,
      },
    ],
  };
  let option2 = {
    // title: {
    //     text: '每人完成实验个数',
    //     left: 'center',
    //     bottom: '5%',
    //   },
    xAxis: {
      type: "category",
      data: piechartmapKeys,
      //data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      axisLabel: {
        color: '#fff'
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: '#fff'
      },
    },
    series: [
      {
        data: piechartmapValues,
        //data: [150, 230, 224, 218, 135, 147, 260],
        type: "line",
        smooth: true,
        lineStyle: {
          // color: 'yellow', // 设置线的颜色为红色
          width: 2, // 设置线宽
        },
        itemStyle: {
          // color: 'yellow', // 设置点的颜色
        },
        symbolSize: 10, // 设置所有点的大小
      },
    ],
  };
  let option3 = {
    // title: {
    //     text: '每人完成实验个数',
    //     left: 'center',
    //     bottom: '5%',
    //   },
    xAxis: {
      type: "category",
      data: piechartmapKeys,
      //data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: piechartmapValues,
        //data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
      },
    ],
  };
  //let chartDom1 = document.getElementById("mychart");
  let chartDom2 = document.getElementById("mychart2");
  //let chartDom3 = document.getElementById("mychart3");
  //let myChart1 = echarts.init(chartDom1);
  let mychart2 = echarts.init(chartDom2);
  //let mychart3 = echarts.init(chartDom3);
  //myChart1.setOption(option);
  mychart2.setOption(option2);
  //mychart3.setOption(option3);
};

const showDataVis = async () => {
  // ElMessage({
  //   type: 'success',
  //   message: '点击了'
  // })
  await getTableData();
  setTimeout(() => {
    getTableData();
  }, 500);
  // ElMessage({
  //   type: 'success',
  //   message: '执行下面了吗？'
  // })
  await getNationCount();
  // ElMessage({
  //   type: 'success',
  //   message: '执行了'
  // })
  setTimeout(() => {
    getTableData();
  }, 500);
  console.log(piechartmap);
  await initcharts();
  setTimeout(() => {
    getTableData();
  }, 500);
  //handleReload()
};

showDataVis();
</script>
  
  <style>
</style>
  